// 临时脚本用于导入CSV数据 - 使用Node.js内置http模块
const http = require('http');
const querystring = require('querystring');

function postData(url, data, token = '') {
  return new Promise((resolve, reject) => {
    const postDataStr = querystring.stringify(data);
    const urlParts = url.split('://')[1].split('/');
    const hostname = urlParts[0].split(':')[0];
    const port = urlParts[0].split(':')[1] || 80;
    const path = '/' + urlParts.slice(1).join('/');

    // 设置请求头
    const headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(postDataStr)
    };

    // 如果提供了token，添加到请求头
    if (token) {
      headers['Authorization'] = 'Bearer ' + token;
    }

    const options = {
      hostname: hostname,
      port: port,
      path: path,
      method: 'POST',
      headers: headers
    };

    const req = http.request(options, (res) => {
      let responseData = '';
      
      res.on('data', (chunk) => {
        responseData += chunk;
      });

      res.on('end', () => {
        try {
          const parsedData = JSON.parse(responseData);
          resolve(parsedData);
        } catch (e) {
          resolve({ code: 500, msg: '响应数据格式错误', data: responseData });
        }
      });
    });

    req.on('error', (e) => {
      reject(e);
    });

    req.write(postDataStr);
    req.end();
  });
}

// 登录获取token
async function login(username, password) {
  console.log(`正在登录系统...`);
  try {
    const response = await postData('http://localhost:8080/login', {
      username: username,
      password: password
    });
    
    console.log('登录响应:', response);
    
    // 检查是否登录成功并返回token
    if (response.code === 200 && response.token) {
      console.log('登录成功，获取到token');
      return response.token;
    } else {
      throw new Error('登录失败: ' + (response.msg || '未知错误'));
    }
  } catch (error) {
    console.error('登录出错:', error.message);
    throw error;
  }
}

async function importCsvData() {
  const filePath = 'c:\\Users\\Administrator\\RuoYi-Vue\\sql\\mediamatch_usermsg_first20000.csv';
  
  console.log('开始导入CSV数据...');
  console.log('文件路径:', filePath);
  
  try {
    // 先登录获取token
    const token = await login('admin', 'admin123');
    
    // 先测试导入2000条数据
    console.log('测试导入2000条数据...');
    const testResponse = await postData('http://localhost:8080/system/guangdian/importCsv', 
      {
        filePath: filePath,
        limit: 2000
      }, token);
    
    console.log('测试导入结果:', testResponse);
    
    // 根据响应结构判断成功条件
    if (testResponse.code === 200 || testResponse.success || testResponse.msg?.includes('成功')) {
      console.log('测试数据导入成功');
      
      // 导入全部数据
      console.log('开始导入全部数据...');
      const fullResponse = await postData('http://localhost:8080/system/guangdian/importCsv',
        {
          filePath: filePath,
          limit: 0
        }, token);
      
      console.log('全部导入结果:', fullResponse);
      
      if (fullResponse.code === 200 || fullResponse.success || fullResponse.msg?.includes('成功')) {
        console.log('全部数据导入成功');
        console.log('\n请访问仪表盘页面查看统计数据:');
        console.log('http://localhost:8080/system/guangdian/dashboard');
      } else {
        console.error('导入全部数据失败:', fullResponse.msg || '未知错误');
      }
    } else {
      console.error('测试数据导入失败:', testResponse.msg || '未知错误');
    }
  } catch (error) {
    console.error('导入失败:', error.message);
  }
}

importCsvData();